#!/usr/bin/env python
# -*- coding: utf-8 -*-

#Piglenti, written in Python programming language allows you to-day tasks easily integrated with pidgin running a small Linux application.
#Copyright (C) 2010  h4ckinger dot gmail dot com
#www.h4ckinger.org

#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.

#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.

#You should have received a copy of the GNU General Public License
#along with this program.  If not, see <http://www.gnu.org/licenses/>.

import dbus, gobject,re
from dbus.mainloop.glib import DBusGMainLoop
from fonks import fonks
from time import sleep

class piglenti:
    """ Main class """
    def __init__(self):
        """Definations"""
        self.pidgin_bus = ("im.pidgin.purple.PurpleService","/im/pidgin/purple/PurpleObject","im.pidgin.purple.PurpleInterface")
        self.pigword    =   "/pig "
        self.fonks      =   fonks(self.pigword)
        self.fonks_name =   "self.fonks" #above variable name
        self.bus        =   None    #bus object
        self.purple     =   None    #purple proxy
        self.loop       =   None    #loop
        self.totalparam =   3       #3 normal 1 text
        try:
            self.dbus_connect()
        except(dbus.exceptions.DBusException):
            print("Dbus couldn't connect")
            exit()
    def dbus_connect(self):
        """ Dbus Connector Function """
        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
        self.bus = dbus.SessionBus()
        obj= self.bus.get_object(self.pidgin_bus[0], self.pidgin_bus[1])
        self.purple = dbus.Interface(obj, self.pidgin_bus[2])
        self.bus.add_signal_receiver(self.process_msg, dbus_interface=self.pidgin_bus[2],signal_name="SentImMsg") #add signal
    def returnFunction(self):
        """ Returns correct function to given @param"""
        return self.fonks.functions[self.fonks.param1]["def"]
    def check_params(self,word):
        """ Check param if valids """        
        return True if word.startswith(self.pigword) and self.fonks.functions.has_key(word[len(self.pigword):].split(" ")[0]) else False
    def process_params(self,msg):
        """ Splits words and sets global params """
        spl     =   msg[len(self.pigword):]
        explode =   spl.split(" ",self.totalparam)        
        try:
            self.fonks.param1=explode[0]
        except IndexError:
            pass
        try:
            self.fonks.param2=explode[1]
        except IndexError:
            pass
        try:
            self.fonks.param3=explode[2]
        except IndexError:
            pass
        try:
            bul=re.search("&quot;(.*?)&quot;",spl)
            self.fonks.paramText=bul.group(1)
        except AttributeError:
            pass
    def clear_params(self):
        """ Sets params to None"""
        self.fonks.param1     =   None    #param1
        self.fonks.param2     =   None    #param2
        self.fonks.param3     =   None    #param3
        self.fonks.paramText  =   None    #paramText
    
    #main part
    def process_msg(self,accountId,receiver,msg):
        """ When SentImMsg emitted process message"""
        if self.check_params(msg):                                      #if true
            self.process_params(msg)                                    #set params
            exc         =   self.returnFunction()                       #get return function
            response    =   eval(self.fonks_name+"."+exc+"()")          #exec function returns string or list
            conv_id     =   self.findConversation(accountId,receiver)   #find conversation id
            self.conversationWrite(conv_id,receiver,response)           #write invisible(default) response
            self.clear_params()                                         #clear all params
    #end main part
    def findConversation(self,accountId,receiver):
        """ Returns conversation id"""
        return self.purple.PurpleFindConversationWithAccount(1,receiver,accountId)
    def conversationWrite(self,conv_id,receiver,msg,gizli=0,ntime=0):
        """ Write message to conversation"""
        if type(msg) == str:
            self.purple.PurpleConversationWrite(conv_id,receiver,"\n"+msg.strip(),gizli,ntime)
        if type(msg) == list:
            sleep_if_too_long=0.1 if len("".join(msg)) > 400 else 0
            for tek in msg:
                self.purple.PurpleConversationWrite(conv_id,receiver,"\n"+tek.strip(),gizli,ntime)
                sleep(sleep_if_too_long)    #sleep if too long else continue
    def start(self):
        """ Start piglenti"""
        self.loop = gobject.MainLoop()
        self.loop.run()

x=piglenti()
x.start()